package com.itheima.tlias84.service.impl;

import com.itheima.tlias84.annotation.Log;
import com.itheima.tlias84.dto.SelectAllDeptDTO;
import com.itheima.tlias84.entity.Dept;
import com.itheima.tlias84.mapper.DeptMapper;
import com.itheima.tlias84.po.InsertDeptParam;
import com.itheima.tlias84.service.DeptService;
import com.itheima.tlias84.utils.ResultUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class DeptServiceImpl implements DeptService {

    @Resource
    DeptMapper deptMapper;
    @Override
    public List<SelectAllDeptDTO> selectAll() {
        List<SelectAllDeptDTO> dtos = deptMapper.selectAll();
        return dtos;
    }

    @Log
    @Override
    public int insertDept(InsertDeptParam param) {
        Dept dept = new Dept();
        dept.setName(param.getName());
        dept.setUpdateTime(LocalDateTime.now());
        dept.setCreateTime(LocalDateTime.now());
        int flag = deptMapper.insertDept(dept);
        return flag;
    }

    @Log
    @Override
    public int deleteById(Integer id) {
        return deptMapper.deleteById(id);
    }

    @Override
    public SelectAllDeptDTO selectDeptById(Integer id) {
        return deptMapper.selectDeptById(id);
    }

    @Log
    @Override
    public ResultUtil updateDeptById(Dept dept) {
        dept.setUpdateTime(LocalDateTime.now());
        //校验部门名称是否重复
        //根据id以及name 查询部门
        Dept selected = deptMapper.selectDeptByName(dept.getName());
        if (Objects.nonNull(selected) && selected.getId() != dept.getId()){
            return ResultUtil.fail("部门名称重复");
        }
        deptMapper.updateDeptById(dept);
        return  ResultUtil.success();

    }

    @Log
    @Override
    public int batchDelete(List<Integer> ids) {
        return  deptMapper.batchDelete(ids);
    }



}
